package com.leonwoodstudio.eventdetectionclient.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.LruCache;

import com.leonwoodstudio.eventdetectionclient.eventmessage.ParsedEventMessageToSave;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by win7 on 2017/4/23.
 */
public class AsyncImageLoader {
    //图片缓存对象
    private static LruCache<String, Bitmap> imageCache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            //在每次存入缓存的时候调用
            return value.getByteCount();
        }
    };  //LruCache缓存对象
    private static Set<ParsedEventMessageToSave> downloading = new HashSet<>();

//    public static byte[] toByteArray(InputStream input) throws IOException {
//        ByteArrayOutputStream output = new ByteArrayOutputStream();
//        byte[] buffer = new byte[4096];
//        int n = 0;
//        while (-1 != (n = input.read(buffer))) {
//            output.write(buffer, 0, n);
//        }
//        return output.toByteArray();
//    }

    //实现图片的异步加载
    public Bitmap loadImage(final ParsedEventMessageToSave parsed, final ImageCallback callback){
        //查询缓存，查看当前需要下载的图片是否已经存在于缓存当中
        if(imageCache.get(parsed.getPic_name()) != null){
            return imageCache.get(parsed.getPic_name());
        }

        String image = FileAccessor.getInstance(null).getFilesDir() + parsed.getPic_name();
        if (FileAccessor.getInstance(null).isFileExist(image)) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(new File(image));
                Bitmap bm = BitmapFactory.decodeStream(fis);
//                byte[] byte_array = toByteArray(fis);
//                Bitmap bm = BitmapFactory.decodeByteArray(byte_array, 0, byte_array.length);
                if (bm != null) {
                    // Somehow decode could fail and return null.
                    imageCache.put(parsed.getPic_name(), bm);
                    return bm;
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } /*catch (IOException e) {
                e.printStackTrace();
            }*/ finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                callback.imageLoaded((Bitmap) msg.obj, parsed);
            }
        };

        if (downloading.contains(parsed)) {
            return null;
        }

        //新开辟一个线程，该线程用于进行图片的下载
        Thread thread = new Thread(){
            @Override
            public void run() {
                downloading.add(parsed);
                Bitmap bitmap = downloadImageFromUrl(parsed);
                downloading.remove(parsed);
                if (bitmap == null) {
                    System.out.println("image download fail");
                    return;
                }
                imageCache.put(parsed.getPic_name(), bitmap);
                Message message = handler.obtainMessage(0, bitmap);
                handler.sendMessage(message);
            }
        };
        thread.start();
        return null;
    }

    protected Bitmap downloadImageFromUrl(ParsedEventMessageToSave parsed) {
        String url = parsed.getUrl();
        String[] url_tokens = url.split("//");
        String url_host = url_tokens[1];
        String url_dir = url_tokens[2];
        //FtpUtil.getInstance().initFTPSetting(url_host, 21, "anonymous", "");
        int try_count = 0;
        while (try_count < 120) {
            FtpUtil.getInstance().waitAndInit(url_host, 21, "Administrator", "csnt123");
            boolean download_success = false;
            String image = FileAccessor.getInstance(null).getFilesDir() + parsed.getPic_name();
            download_success = FtpUtil.getInstance().downLoadFile(image, url_dir, parsed.getPic_name());
            if (download_success) {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(new File(image));
                    return BitmapFactory.decodeStream(fis);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            // Somehow fails.
            try_count++;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //回调接口
    public interface ImageCallback{
        void imageLoaded(Bitmap imageBitmap, ParsedEventMessageToSave parsed);
    }
}
